package com.wantong.jianpu.viewmodels;

import android.app.Application;

import androidx.annotation.NonNull;

import com.wantong.jianpu.base.BaseResultBean;
import com.wantong.jianpu.beans.DictBean;
import com.wantong.jianpu.beans.FaultCommitBean;
import com.wantong.jianpu.beans.InspectionDetailBean;
import com.wantong.jianpu.beans.LocationBean;
import com.wantong.jianpu.beans.SelectImageBean;
import com.wantong.jianpu.beans.TourCommitBean;
import com.wantong.jianpu.beans.UpLoadBean;
import com.wantong.jianpu.beans.UploadFileBean;
import com.wantong.jianpu.event.TourDetailEvent;
import com.wantong.jianpu.models.FaultModel;
import com.wantong.jianpu.models.LocationModel;
import com.wantong.jianpu.models.UpLoadModel;
import com.wantong.jianpu.net.BaseObserver;
import com.wantong.jianpu.utils.Constants;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.JsonUtil;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * @author PACY
 * @date 2022/5/7
 * description:
 */
public class CreateTourViewModel extends BaseViewModel {
    public String id;
    public int currentNum;//当前巡检次数
    public LocationModel locationModel;
    public FaultModel model;
    public UpLoadModel upLoadModel;

    public SingleLiveEvent<TourCommitBean> commitData=new SingleLiveEvent<>();
    public SingleLiveEvent<List<SelectImageBean>> image=new SingleLiveEvent<>();//回显的图片
    public SingleLiveEvent<String> location= new SingleLiveEvent<>();//位置信息
    public SingleLiveEvent<String[]> locationDialogEvent= new SingleLiveEvent<>();//位置信息
    public List<LocationBean> locationBeans;

    public SingleLiveEvent<String> grade=new SingleLiveEvent<>();//维修级别
    public SingleLiveEvent<String[]> gradeDialogEvent=new SingleLiveEvent<>();

    public SingleLiveEvent<String> range= new SingleLiveEvent<>();//保养范围
    public SingleLiveEvent<String[]> rangeDialogEvent= new SingleLiveEvent<>();
    public List<DictBean> rangeBeans;


    public CreateTourViewModel(@NonNull Application application) {
        super(application);
        locationModel=new LocationModel();
        model=new FaultModel();
        upLoadModel=new UpLoadModel();
        commitData.setValue(new TourCommitBean());
        commitData.getValue().setImageList(new ArrayList<>());
    }

    @Override
    protected void init() {
        super.init();
        getLocationRequest();
        getRangeRequest();
        if(StringUtils.isNotEmpty(SPUtils.getInstance(Constants.TOUR).getString("data",""))){//有历史记录  回显
            TourCommitBean bean=JsonUtil.jsonToObject(SPUtils.getInstance(Constants.TOUR).getString("data",""),TourCommitBean.class);
            commitData.setValue(bean);
            location.setValue(bean.getLocationName());
            grade.setValue(bean.getMaintainLevel());
            range.setValue(bean.getMaintainScopeName());

            if(bean.getImageList()!=null){
                List<SelectImageBean> imageBeans=new ArrayList<>();
                for (UploadFileBean faultFile : bean.getImageList()) {
                    SelectImageBean imageBean=new SelectImageBean();
                    imageBean.setFileName(faultFile.getFileName());
                    imageBean.setNet(true);
                    imageBean.setUrl(faultFile.getUrl());
                    imageBeans.add(imageBean);
                }
                image.setValue(imageBeans);
            }
        }
    }


    /**
     * 提交
     */
    public BindingCommand commit=new BindingCommand(() -> {
        if(commitData.getValue().getLocationId()==0){
            ToastUtils.show("请选择巡检位置");
            return;
        }
        if(StringUtils.isEmpty(commitData.getValue().getMaintainLevel())){
            ToastUtils.show("请选择级别");
            return;
        }
        if(StringUtils.isEmpty(commitData.getValue().getMaintainScope())){
            ToastUtils.show("请选择保养范围");
            return;
        }
        if(StringUtils.isEmpty(commitData.getValue().getMaintainRecord())){
            ToastUtils.show("请输入保养记录");
            return;
        }
        if(StringUtils.isEmpty(commitData.getValue().getMaintainResult())){
            ToastUtils.show("请输入保养结果");
            return;
        }
        if(commitData.getValue().getImageList()==null||commitData.getValue().getImageList().isEmpty()){
            ToastUtils.show("请上传巡检照片");
            return;
        }

        commitData.getValue().setInspetionId(id);
        commitData.getValue().setCurrentNum(currentNum);

        model.inspection_record(JsonUtil.objectToJson(commitData.getValue()), new BaseObserver() {
            @Override
            public void onSuccess(BaseResultBean t) {
                ToastUtils.show("提交成功");
                SPUtils.getInstance(Constants.TOUR).clear();
                EventBus.getDefault().post(new TourDetailEvent());
                finish();
            }

        },getLifecycleProvider());
    });

    /**
     * 保存为草稿
     */
    public BindingCommand save=new BindingCommand(() -> {
        SPUtils.getInstance(Constants.TOUR).put("data",JsonUtil.objectToJson(commitData.getValue()));
        ToastUtils.show("保存草稿成功");
    });

    /**
     * 维修等级
     */
    public BindingCommand selectGrade=new BindingCommand(() -> {
        gradeDialogEvent.setValue(new String[]{"日(日常)", "月(初级)","季(中级)","年(高级)","特殊"});
    });

    /**
     * 设置维修等级
     * @param str
     */
    public void setGrade(String str){
        grade.setValue(str);
        commitData.getValue().setMaintainLevel(str);
    }


    /**
     * 选择位置信息
     */
    public BindingCommand selectLocation=new BindingCommand(() -> {
        if (locationBeans!= null) {
            String[] brand = new String[locationBeans.size()];
            for (int i = 0; i < locationBeans.size(); i++) {
                brand[i] = locationBeans.get(i).getName();
            }
            locationDialogEvent.setValue(brand);
        } else {
            getLocationRequest();
        }
    });
    /**
     * 选择位置信息
     */
    public void setLocationPosition(int position) {
        if (locationBeans != null) {
            location.setValue(locationBeans.get(position).getName());
            commitData.getValue().setLocationId(locationBeans.get(position).getId());
            commitData.getValue().setLocationName(locationBeans.get(position).getName());
        }
    }


    /**
     * 获取位置信息
     */
    private void getLocationRequest(){
        locationModel.getInspectionLocation(new BaseObserver<List<LocationBean>>() {
            @Override
            public void onSuccess(BaseResultBean<List<LocationBean>> t) {
                locationBeans=t.getData();
            }
        },getLifecycleProvider());
    }


    /**
     * 选择保养范围
     */
    public BindingCommand selectRange=new BindingCommand(() -> {
        if (rangeBeans!= null) {
            String[] brand = new String[rangeBeans.size()];
            for (int i = 0; i < rangeBeans.size(); i++) {
                brand[i] = rangeBeans.get(i).getDictLabel();
            }
            rangeDialogEvent.setValue(brand);
        } else {
            getRangeRequest();
        }
    });
    /**
     * 选择保养范围
     */
    public void setRangePosition(int position) {
        if (rangeBeans != null) {
            range.setValue(rangeBeans.get(position).getDictLabel());
            commitData.getValue().setMaintainScope(rangeBeans.get(position).getDictValue());
            commitData.getValue().setMaintainScopeName(rangeBeans.get(position).getDictLabel());
        }
    }


    /**
     * 获取保养范围
     */
    private void getRangeRequest(){
        model.scope(new BaseObserver<List<DictBean>>() {
            @Override
            public void onSuccess(BaseResultBean<List<DictBean>> t) {
                rangeBeans=t.getData();
            }
        },getLifecycleProvider());
    }


    /**
     * 上传文件
     * @param filePath
     */
    public void upLoadFile(List<String> filePath){
        showDialog();
        upLoadModel.upLoadImages(filePath, new BaseObserver<List<UpLoadBean>>() {
            @Override
            public void onSuccess(BaseResultBean<List<UpLoadBean>> t) {
                for (UpLoadBean datum : t.getData()) {
                    UploadFileBean fileBean=new UploadFileBean();
                    fileBean.setUrl(datum.getUrl());
                    fileBean.setFileName(datum.getFileName());
                    commitData.getValue().getImageList().add(fileBean);
                }
            }

            @Override
            public void onComplete() {
                super.onComplete();
                dismissDialog();
            }
        },getLifecycleProvider());
    }
}
